package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CacheClient cacheClient;
    @Override
    public Result selectById(Long id) {
        log.info("id = {}",id);
        Shop shop = cacheClient.queryWithLogicalExpire(
                RedisConstants.LOCK_SHOP_KEY ,
                RedisConstants.CACHE_SHOP_KEY ,
                id, Shop.class, aLong -> getById(aLong), RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS
        );
        if (shop == null){
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    @Override
    public Result queryShopById(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    private final static ExecutorService EXECUTORTreedPOOL = Executors.newFixedThreadPool(10);

    public Shop queryWithLogicalExpire(Long id) {

        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //从缓存中查询数据
        String json = redisTemplate.opsForValue().get(key);
        //如果没有缓存 直接返回null
        if (StrUtil.isBlank(json)){
            return null;
        }
        //转换成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //判断缓存是否过期
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //没有过期
            log.info("缓存没有过期 直接返回");
            return shop;
        }
        //已经过期了 进行缓存重建
        //获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + key;
        boolean lock = tryLock(lockKey);
        if (lock){//拿到锁
            //开启新的线程
            EXECUTORTreedPOOL.submit(()->{
                log.info("进行缓存重建...");
                //进行重建
                try {
                    save2RedisData(id,20L);
                } catch (Exception e) {
                   // e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {//释放锁
                    unlock(lockKey);
                }
            });
        }
        return shop;
    }


    public void save2RedisData(Long id,Long expireTime){
        //缓存预热
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));

    }








    public Shop queryWithMutex(Long id){
        String key  = RedisConstants.CACHE_SHOP_KEY + id;
        //从redis 查询缓存
        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)){
            log.info("缓存中存在直接返回！");
            //存在直接返回
            Shop shop = JSONUtil.toBean(json, Shop.class);
            return shop;
        }
        if (json != null){//缓存的为空值
            return null;
        }
        Shop shop = null;
        //不存在从数据库查询
        //获取互斥锁
        String lock = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            boolean isLock = tryLock(lock);
            if (!isLock){
                //没有获取到锁
                Thread.sleep(50);
                //4.3 失败，则休眠重试
                return queryWithMutex(id);
            }
            //获取到了锁 查询数据库
            log.info("redis中不存在 查询数据库");
            shop = getById(id);
            //不存在返回错误
            if (shop == null){
                //使用缓存空值解决 缓存穿透
                redisTemplate.opsForValue().set("RedisConstants.CACHE_SHOP_KEY"+id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.SECONDS);
                return null;
            }
            //存在 存入redis 返回
            redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lock);
        }
        return shop;
    }
    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

}
